<?php

namespace App\Models;

use Exception;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Support\Facades\DB;

/**
 * 满意度用户答题表
 * Class SurveyApplyModel
 * @package app\common\model
 */
class SatisfactionSurveyReply extends BaseModel
{
    use HasFactory;

    const CREATED_AT = 'create_time';
    const UPDATED_AT = 'change_time';

    public $table = "satisfaction_survey_reply";

    /*关联用户*/
    public function conUser()
    {
        return $this->hasOne(UserInfo::class, 'id', 'user_id');
    }

    /**
     * 问卷调查用户回复列表
     * @param limit 限制条数 默认为 10
     * @param survey_id 问卷调查id
     * @param keywords 检索内容
     * @param is_satisfaction int 是否满意  1 满意  2 不满意
     * @param status int 是否核销  1 以核销  2 未核销（时间已过）3 待核销
     * @param start_time datetime 活动开始时间    数据格式  年月日
     * @param end_time datetime 活动结束时间
     * @param qr_code datetime 核销码
     */
    public function lists($survey_id, $user_id, $keywords, $is_satisfaction, $status, $start_time, $end_time, $qr_code, $limit = 10)
    {
        $res = $this->select(
            'id',
            'survey_id',
            'user_id',
            'username',
            'tel',
            'is_satisfaction',
            'intro',
            'date',
            'create_time',
            'change_time',
            'qr_code',
            'status',
            'draw_time',
            DB::raw("if(status = 3,1,0) as order_num")
        )
            ->where(function ($query) use ($keywords) {
                if ($keywords) {
                    $query->where('username', 'like', '%' . $keywords . '%')
                        ->orWhere('tel', 'like', '%' . $keywords . '%')
                        ->orWhere('qr_code', 'like', '%' . $keywords . '%');
                }
            })->where(function ($query) use ($survey_id, $user_id, $is_satisfaction, $status, $start_time, $end_time, $qr_code) {
                if ($survey_id) {
                    $query->where('survey_id', $survey_id);
                }
                if ($user_id) {
                    $query->where('user_id', $user_id);
                }
                if ($is_satisfaction) {
                    $query->where('is_satisfaction', $is_satisfaction);
                }
                if ($qr_code) {
                    $query->where('qr_code', $qr_code);
                }
                if ($status) {
                    if (!is_array($status)) {
                        $status = explode(',', $status);
                    }
                    $query->whereIn('status', $status);
                }
                if ($start_time && $end_time) {
                    $query->whereBetween('create_time', [$start_time, $end_time]);
                }
            })
            ->orderByDesc('order_num')
            ->orderByDesc('create_time')
            ->paginate($limit)
            ->toArray();

        foreach ($res['data'] as $key => $val) {
            if ($val['user_id']) {
                $wechat_info = UserInfo::getWechatField($val['user_id'], ['nickname', 'head_img']);
                if ($wechat_info) {
                    $res['data'][$key]['nickname'] = $wechat_info['nickname'];
                    $res['data'][$key]['head_img'] = $wechat_info['head_img'];
                } else {
                    $res['data'][$key]['nickname'] = null;
                    $res['data'][$key]['head_img'] = null;
                }
            } else {
                $res['data'][$key]['nickname'] = null;
                $res['data'][$key]['head_img'] = null;
            }
            $res['data'][$key]['survey_name'] = SatisfactionSurvey::where('id', $val['survey_id'])->value('survey_name');
        }
        return $res;
    }

    /**
     * 进行核销
     * @param id 申请id  二选一
     * @param qr_code 核销码
     */
    public function verification($id = null, $qr_code = null)
    {
        if (empty($id) && empty($qr_code)) {
            throw new Exception('参数错误');
        }

        $res = $this->where(function ($query) use ($id, $qr_code) {
            if (!empty($id)) {
                $query->where('id', $id);
            } else {
                $query->where('qr_code', $qr_code);
            }
        })->first();
        if (empty($res)) {
            throw new Exception('记录不存在');
        }
        if ($res->date != date('Y-m-d')) {
            throw new Exception('核销时间已过');
        }
        if ($res->status != 3) {
            throw new Exception('此状态不允许核销');
        }
        $res->status = 1;
        $res->draw_time = date('Y-m-d H:i:s');
        return $res->save();
    }

    /**
     * 获取用户提交次数
     * @param survey_id 问卷调查id
     * @param user_id 用户id
     * @param date 日期
     * @param is_satisfaction 是否满意  1 满意  2 不满意
     */
    public function getUserSubmitCount($survey_id = null, $user_id = null, $date = null, $is_satisfaction = null)
    {
        $number = $this->where(function ($query) use ($survey_id, $user_id, $date, $is_satisfaction) {
            if ($date) {
                $query->where('date', $date);
            }
            if ($user_id) {
                $query->where('user_id', $user_id);
            }
            if ($survey_id) {
                $query->where('survey_id', $survey_id);
            }
            if ($is_satisfaction) {
                $query->where('is_satisfaction', $is_satisfaction);
            }
        })->count();
        return $number;
    }

    /**
     * 判断是否可以提交
     * @param survey_id 问卷调查id
     * @param user_id 用户id
     */
    public function isCanSubmit($data, $survey_id, $user_id)
    {
        //获取用户提交次数
        $is_can_submit = true;
        $not_submit_msg = '';
        $user_submit_count = $this->getUserSubmitCount($survey_id, $user_id);
        if (empty($user_submit_count)) {
            $is_can_submit = true; //可以提交
        } else {
            if ($data['total_number'] <= $user_submit_count) {
                $is_can_submit = false;
                $not_submit_msg = '已提交，请勿重复提交';
            } else {
                $day_user_submit_count = $this->getUserSubmitCount($survey_id, $user_id, date('Y-m-d'));
                if ($data['day_number'] <= $day_user_submit_count) {
                    $is_can_submit = false;
                    $not_submit_msg = '今日已提交，请勿重复提交';
                }
            }
        }
        return [$is_can_submit, $not_submit_msg];
    }
}
